// 2025.5.29晚版本，可以实现全部功能与单个通道映射，但无法在串口屏显示
/**
 * Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 * Description: SLE GATEWAY Sample Source with ADC data detection and transmission. 
 *
 * History: 
 * 2023-07-17, Create file. 
 * 改进说明：检测ADC值并每隔固定时间（可根据宏定义修改），通过服务端串口发送检测到的ADC数据，且不影响服务端接收数据并传送给客户端的操作 
 */
#include "securec.h"
#include "sle_uart_server.h"
#include "sle_uart_server_adv.h"
#include "sle_device_discovery.h"
#include "sle_errcode.h"
#include "common_def.h"
#include "soc_osal.h"
#include "app_init.h"
#include "pinctrl.h"
#include "uart.h"
#include "sle_low_latency.h"
#include "adc.h"
#include "adc_porting.h"
#include "osal_debug.h"
#include "cmsis_os2.h"
#include <string.h>
#include <math.h>  // 用于数学计算 

#define CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_SERVER    1
#define CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_CLIENT    0  // 0=服务器模式，1=客户端模式
#define CONFIG_SLE_GATEWAY_BUS                      0 
#define CONFIG_UART_TXD_PIN                         15 
#define CONFIG_UART_RXD_PIN                         16 

#define UART_RX_CONDITION_MASK_IDLE                 1
#define UART_RX_CONDITION_MASK_SUFFICIENT_DATA      2
#define UART_RX_CONDITION_MASK_FULL                 4
#define UART_RX_CONDITION_FULL_OR_SUFFICIENT_DATA_OR_IDLE \
    (UART_RX_CONDITION_MASK_FULL | UART_RX_CONDITION_MASK_SUFFICIENT_DATA | UART_RX_CONDITION_MASK_IDLE)

// 任务配置
#define SLE_GATEWAY_TASK_STACK_SIZE            0x1200 
#define SLE_GATEWAY_TASK_PRIO                  28 
#define SLE_GATEWAY_TASK_DURATION_MS           2000 
 
// ADC配置 
#define ADC_TASK_STACK_SIZE        0x1000
#define ADC_TASK_PRIO              (osPriority_t)(17)
#define ADC_SAMPLE_INTERVAL_MS     500 
#define ADC_FILTER_WINDOW_SIZE     3 
#define ADC_SEND_INTERVAL_MS       1000
#define ADC_MAX_RAW_VALUE          4095    // 12位ADC
#define ADC_REF_VOLTAGE            3300    // 3.3V参考电压(mV)
 
// 串口配置 
#define SLE_GATEWAY_BAUDRATE                   115200 
#define SLE_GATEWAY_TRANSFER_SIZE              256 
static uint8_t g_app_uart_rx_buff[SLE_GATEWAY_TRANSFER_SIZE] = { 0 };
static uart_buffer_config_t g_app_uart_buffer_config = {
    .rx_buffer = g_app_uart_rx_buff,
    .rx_buffer_size = SLE_GATEWAY_TRANSFER_SIZE 
};
 
/* ADC通道配置 */
static const uint8_t g_adc_channels[] = {0, 1, 2, 3, 4, 5}; // CH0~CH5 
#define ADC_CHANNEL_COUNT (sizeof(g_adc_channels)/sizeof(g_adc_channels[0]))
/* 修改通道处理配置结构体 */
typedef double (*transform_func_t)(uint16_t);  // 明确函数指针类型 

/* 通道处理配置结构体 */
typedef struct {
    uint8_t channel;
    double scale;                   // 缩放系数
    double offset;                  // 偏移量
    const char *unit;               // 单位 
    transform_func_t transform;     // 使用统一定义的函数指针类型 
} adc_channel_config_t;
 
/**
 ****************************************************************************************************
 * 驱动函数区
 ****************************************************************************************************
 */
#define TS_K 2047.19

// 返回原始值
static double original_value(uint16_t value)
{
    return value;
}

// 烟雾传感器           3v3
static double sensor_map_smog(uint16_t smog) 
{
    double Vol = (smog*3.3/4096);
	double RS = (3.3-Vol)/(Vol*4.7);// RL=4.7kΩ 
	double R0=6.64; // 需要根据实际校准 
	
	double MQ_2_DAT = pow(11.5428*R0/RS, 0.6549f);

    return MQ_2_DAT;
}

//可燃气体传感器        3v3
static double sensor_map_combustible_gas(uint16_t combustible_gas)
{
    double Vol = (combustible_gas*3.3/4096);
	double RS = (3.3-Vol)/(Vol*0.5); // RL=0.5kΩ
	double R0=6.64; // 需要根据实际校准 
	
	double MQ_5_DAT = pow(11.5428*R0/RS, 0.6549f);

    return MQ_5_DAT;
}

//一氧化碳传感器        3v3
static double sensor_map_carbon_monoxide(uint16_t carbon_monoxide)
{
    double Vol = (carbon_monoxide*3.3/4096);
	double RS = (3.3-Vol)/(Vol*0.5); // RL=0.5kΩ
	double R0=6.64; // 需要根据实际校准 
	
	double MQ_7_DAT = pow(11.5428*R0/RS, 0.6549f);

    return MQ_7_DAT;
}

//水下
//电导率传感器          3v3/5v
static double sensor_map_conductivity(uint16_t smconductivityog)
{
    double TDS_DAT;
    TDS_DAT = (smconductivityog/4095.0)*3.3;//转换为电压值
	TDS_DAT = 66.71*TDS_DAT*TDS_DAT*TDS_DAT-127.93*TDS_DAT*TDS_DAT+428.7*TDS_DAT;//转换为PPM值// 保持原有多项式计算（系数可能需要重新校准） 
	
    if(TDS_DAT<20) TDS_DAT = 0;
    
    return TDS_DAT;
}

//浊度传感器            3v3
static double sensor_map_turbidity(uint16_t turbidity)
{
    double TS_DAT;
	TS_DAT = (turbidity/4096.0)*3.3;//转换为电压值
	TS_DAT = -865.68*TS_DAT+TS_K;//转换为PPM值// 线性公式需要重新校准

	if(TS_DAT<35) TS_DAT = 0;
    
    return TS_DAT;
}

//PH酸碱度传感器        3v3
static double sensor_map_pH_value(uint16_t pH_value)
{
    double PH_DAT;
	PH_DAT = (pH_value/4096.0)*3.3;//转换为电压值
	PH_DAT = -5.7541*PH_DAT+16.654;//转换为PPM值// 线性公式需要重新校准 
	
	if(PH_DAT>14.0)PH_DAT=14.0;
	if(PH_DAT<0)PH_DAT=0.0;

    return PH_DAT;
}

/* 通道配置表 - 可根据实际传感器修改 */
/*
    第一个参数：ADC硬件通道号
    第二个参数：输出值的缩放系数（线性比例因子）
    第三个参数：输出值的偏移量（线性补偿值）
    第四个参数：物理量单位（字符串表示）
    第五个参数：传感器专用映射函数指针 
*/
static adc_channel_config_t g_adc_configs[] = {
    {0, 1.0, 0.0, "\xFF\xFF\xFF", sensor_map_smog},                           // CH0: 烟雾 
    {1, 1.0, 0.0, "\xFF\xFF\xFF", sensor_map_combustible_gas},               // CH1: 可燃气体
    {2, 1.0, 0.0, "\xFF\xFF\xFF", sensor_map_carbon_monoxide},               // CH2: 一氧化碳 
    {3, 0.5, 50.0, "\xFF\xFF\xFF", sensor_map_conductivity},                  // CH3: 电导率
    {4, 1.0, 0.0, "\xFF\xFF\xFF", sensor_map_turbidity},                     // CH4: 浊度
    {5, 1.0, 0.0, "\xFF\xFF\xFF", sensor_map_pH_value}                         // CH5: PH
};

/* 滑动平均滤波数据结构 */
typedef struct {
    uint32_t buffer[ADC_FILTER_WINDOW_SIZE];
    uint8_t index;
    uint32_t sum;
} adc_filter_t;

static adc_filter_t g_adc_filters[ADC_CHANNEL_COUNT];
 
/* 初始化滤波器 */
static void adc_filter_init(void) {
    memset(g_adc_filters, 0, sizeof(g_adc_filters));
}
 
/* 滑动平均滤波计算 */
static uint32_t adc_filter_update(uint8_t ch_idx, uint32_t new_value) {
    adc_filter_t *f = &g_adc_filters[ch_idx];
    f->sum -= f->buffer[f->index];
    f->buffer[f->index] = new_value;
    f->sum += new_value;
    f->index = (f->index + 1) % ADC_FILTER_WINDOW_SIZE;
    return f->sum / ADC_FILTER_WINDOW_SIZE;
}
 
/* ADC数据处理和发送函数 */
static void process_and_send_adc(uint8_t ch, uint32_t raw_value) {
    // 查找通道配置
    adc_channel_config_t *config = NULL;
    for (size_t i = 0; i < sizeof(g_adc_configs)/sizeof(g_adc_configs[0]); i++) {
        if (g_adc_configs[i].channel == ch) {
            config = &g_adc_configs[i];
            break;
        }
    }
    if (!config) return;
 
    // 原始值转换为电压(mV)
    double processed_value;
    if (config->transform) {
        processed_value = config->transform((uint16_t)raw_value);
    } else {
        double voltage = (double)raw_value * ADC_REF_VOLTAGE / ADC_MAX_RAW_VALUE;
        processed_value = voltage * config->scale + config->offset;
    }
 
    // 生成发送字符串
    char send_str[64];
    int len = snprintf(send_str, sizeof(send_str), "t%d.txt=%.2f\xFF\xFF\xFF\r\n", 
                      ch, processed_value);

    if (len > 0) {
        // 本地打印
        // osal_printk("%s", send_str);
        uapi_uart_write(CONFIG_SLE_GATEWAY_BUS, (uint8_t *)send_str, len, 0);
        /* 发送给客户端（改为发送格式化字符串） */
        if (sle_uart_client_is_connected()) {
            sle_uart_server_send_report_by_handle((const void *)send_str, strlen(send_str));
        }
    }
}

/* ADC回调函数 */
void test_adc_callback(uint8_t ch, uint32_t *buffer, uint32_t length, bool *next) {
    uint8_t ch_idx = 0;
    for (; ch_idx < ADC_CHANNEL_COUNT; ch_idx++) {
        if (g_adc_channels[ch_idx] == ch) break;
    }
    if (ch_idx >= ADC_CHANNEL_COUNT) {
        *next = false;
        return;
    }
 
    uint32_t raw_value = buffer[0];
    uint32_t filtered_value = adc_filter_update(ch_idx, raw_value);
    process_and_send_adc(ch, filtered_value);
    *next = true;
}
 
/* UART初始化配置 */
static void uart_init_config(void) {
    uart_attr_t attr = {
        .baud_rate = SLE_GATEWAY_BAUDRATE,
        .data_bits = UART_DATA_BIT_8,
        .stop_bits = UART_STOP_BIT_1,
        .parity = UART_PARITY_NONE 
    };
 
    uart_pin_config_t pin_config = {
        .tx_pin = CONFIG_UART_TXD_PIN,
        .rx_pin = CONFIG_UART_RXD_PIN,
        .cts_pin = PIN_NONE,
        .rts_pin = PIN_NONE 
    };
    
    uapi_uart_deinit(CONFIG_SLE_GATEWAY_BUS);
    uapi_uart_init(CONFIG_SLE_GATEWAY_BUS, &pin_config, &attr, NULL, &g_app_uart_buffer_config);
}
 
/* ADC采样任务 */
static void *adc_sample_task(const char *arg) {
    UNUSED(arg);
    osal_printk("ADC Sample Task Started\r\n");
    
    adc_filter_init();
    uapi_adc_init(ADC_CLOCK_500KHZ);
    uapi_adc_power_en(AFE_SCAN_MODE_MAX_NUM, true);
 
    adc_scan_config_t config = {
        .type = 0,
        .freq = 1,
        .long_sample_time = 1,
    };
 
    while (1) {
        for (uint8_t i = 0; i < ADC_CHANNEL_COUNT; i++) {
            uint8_t ch = g_adc_channels[i];
            uapi_adc_auto_scan_ch_enable(ch, config, test_adc_callback);
            osal_msleep(10);
            uapi_adc_auto_scan_ch_disable(ch);
        }
        osal_msleep(ADC_SAMPLE_INTERVAL_MS);
    }
    return NULL;
}
 
/* ADC数据发送任务 */
static void *send_adc_data_task(const char *arg) {
    UNUSED(arg);
    while (1) {
        for (uint8_t i = 0; i < ADC_CHANNEL_COUNT; i++) {
            uint8_t ch = g_adc_channels[i];
            uint32_t filtered_value = g_adc_filters[i].sum / ADC_FILTER_WINDOW_SIZE;
            process_and_send_adc(ch, filtered_value);
        }
        osal_msleep(ADC_SEND_INTERVAL_MS);
    }
    return NULL;
}
 
 
/* --------------------- 服务器模式相关代码 --------------------- */
#if defined(CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_SERVER) && (!defined(CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_CLIENT) || CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_CLIENT == 0)

#define SLE_GATEWAY_SERVER_DELAY_COUNT         5 
#define SLE_ADV_HANDLE_DEFAULT                 1 
#define SLE_GATEWAY_SERVER_MSG_QUEUE_LEN       5
#define SLE_GATEWAY_SERVER_MSG_QUEUE_MAX_SIZE  32 
#define SLE_GATEWAY_SERVER_QUEUE_DELAY         0xFFFFFFFF 
#define SLE_GATEWAY_SERVER_BUFF_MAX_SIZE       800 
#ifdef CONFIG_SAMPLE_SUPPORT_PERFORMANCE_TYPE 
#define SLE_GATEWAY_SERVER_SEND_BUFF_MAX_LEN   250
#else 
#define SLE_GATEWAY_SERVER_SEND_BUFF_MAX_LEN   40
#endif
unsigned long g_sle_uart_server_msgqueue_id;
#define SLE_GATEWAY_SERVER_LOG                 "[sle uart server]" 
 
static void ssaps_server_read_request_cbk(uint8_t server_id, uint16_t conn_id, ssaps_req_read_cb_t *read_cb_para,
    errcode_t status)
{
    osal_printk("%s ssaps read request cbk callback server_id:%x, conn_id:%x, handle:%x, status:%x\r\n",
        SLE_GATEWAY_SERVER_LOG, server_id, conn_id, read_cb_para->handle, status);
}
 
static void ssaps_server_write_request_cbk(uint8_t server_id, uint16_t conn_id, ssaps_req_write_cb_t *write_cb_para,
    errcode_t status)
{
    osal_printk("%s ssaps write request callback cbk server_id:%x, conn_id:%x, handle:%x, status:%x\r\n",
        SLE_GATEWAY_SERVER_LOG, server_id, conn_id, write_cb_para->handle, status);
    if ((write_cb_para->length > 0) && write_cb_para->value) {
        // 确保字符串以null结尾 
        char *text_data = (char *)write_cb_para->value;
        if (text_data[write_cb_para->length-1] != '\0') {
            char temp_buf[write_cb_para->length+1];
            memcpy(temp_buf, write_cb_para->value, write_cb_para->length);
            temp_buf[write_cb_para->length] = '\0';
            text_data = temp_buf;
        }
        
        osal_printk("\n sle uart received data : %s\r\n", text_data);
        uapi_uart_write(CONFIG_SLE_GATEWAY_BUS, (uint8_t *)text_data, strlen(text_data), 0);
    }
}
 
static void sle_uart_server_read_int_handler(const void *buffer, uint16_t length, bool error)
{
    unused(error);
    if (sle_uart_client_is_connected()) {
        sle_uart_server_send_report_by_handle(buffer, length);
    } else {
        osal_printk("%s sle client is not connected! \r\n", SLE_GATEWAY_SERVER_LOG);
    }
}
 
static void sle_uart_server_create_msgqueue(void)
{
    if (osal_msg_queue_create("sle_uart_server_msgqueue", SLE_GATEWAY_SERVER_MSG_QUEUE_LEN, \
        (unsigned long *)&g_sle_uart_server_msgqueue_id, 0, SLE_GATEWAY_SERVER_MSG_QUEUE_MAX_SIZE) != OSAL_SUCCESS) {
        osal_printk("^%s sle_uart_server_create_msgqueue message queue create failed!\n", SLE_GATEWAY_SERVER_LOG);
    }
}
 
static void sle_uart_server_delete_msgqueue(void)
{
    osal_msg_queue_delete(g_sle_uart_server_msgqueue_id);
}
 
static void sle_uart_server_write_msgqueue(uint8_t *buffer_addr, uint16_t buffer_size)
{
    osal_msg_queue_write_copy(g_sle_uart_server_msgqueue_id, (void *)buffer_addr, \
                              (uint32_t)buffer_size, 0);
}
 
static int32_t sle_uart_server_receive_msgqueue(uint8_t *buffer_addr, uint32_t *buffer_size)
{
    return osal_msg_queue_read_copy(g_sle_uart_server_msgqueue_id, (void *)buffer_addr, \
                                    buffer_size, SLE_GATEWAY_SERVER_QUEUE_DELAY);
}
 
static void sle_uart_server_rx_buf_init(uint8_t *buffer_addr, uint32_t *buffer_size)
{
    *buffer_size = SLE_GATEWAY_SERVER_MSG_QUEUE_MAX_SIZE;
    (void)memset_s(buffer_addr, *buffer_size, 0, *buffer_size);
}
 
static void *sle_uart_server_task(const char *arg)
{
    unused(arg);
    uint8_t rx_buf[SLE_GATEWAY_SERVER_MSG_QUEUE_MAX_SIZE] = {0};
    uint32_t rx_length = SLE_GATEWAY_SERVER_MSG_QUEUE_MAX_SIZE;
    uint8_t sle_connect_state[] = "sle_dis_connect";
 
    sle_uart_server_create_msgqueue();
    sle_uart_server_register_msg(sle_uart_server_write_msgqueue);
    sle_uart_server_init(ssaps_server_read_request_cbk, ssaps_server_write_request_cbk);
 
    uart_init_config();
 
    uapi_uart_unregister_rx_callback(CONFIG_SLE_GATEWAY_BUS);
    errcode_t ret = uapi_uart_register_rx_callback(CONFIG_SLE_GATEWAY_BUS,
                                                   UART_RX_CONDITION_FULL_OR_SUFFICIENT_DATA_OR_IDLE,
                                                   1, sle_uart_server_read_int_handler);
    if (ret != ERRCODE_SUCC) {
        osal_printk("%s Register uart callback fail.[%x]\r\n", SLE_GATEWAY_SERVER_LOG, ret);
        return NULL;
    }
    
    // 创建ADC任务
    osal_task *adc_sample_task_handle = osal_kthread_create((osal_kthread_handler)adc_sample_task, 
                                                          0, "ADCSampleTask", ADC_TASK_STACK_SIZE);
    if (adc_sample_task_handle != NULL) {
        osal_kthread_set_priority(adc_sample_task_handle, ADC_TASK_PRIO);
    }
    
    osal_task *send_adc_task_handle = osal_kthread_create((osal_kthread_handler)send_adc_data_task, 
                                                        0, "SendADCTask", ADC_TASK_STACK_SIZE);
    if (send_adc_task_handle != NULL) {
        osal_kthread_set_priority(send_adc_task_handle, ADC_TASK_PRIO);
    }
 
    while (1) {
        sle_uart_server_rx_buf_init(rx_buf, &rx_length);
        sle_uart_server_receive_msgqueue(rx_buf, &rx_length);
        if (strncmp((const char *)rx_buf, (const char *)sle_connect_state, sizeof(sle_connect_state)) == 0) {
            ret = sle_start_announce(SLE_ADV_HANDLE_DEFAULT);
            if (ret != ERRCODE_SLE_SUCCESS) {
                osal_printk("%s sle_connect_state_changed_cbk,sle_start_announce fail :%02x\r\n",
                    SLE_GATEWAY_SERVER_LOG, ret);
            }
        }
        osal_msleep(SLE_GATEWAY_TASK_DURATION_MS);
    }
    sle_uart_server_delete_msgqueue();
    return NULL;
}

/* --------------------- 客户端模式相关代码 --------------------- */
#elif defined(CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_CLIENT) && CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_CLIENT == 1

#define SLE_GATEWAY_TASK_STACK_SIZE            0x1000 
#include "sle_connection_manager.h"
#include "sle_ssap_client.h"
#include "sle_uart_client.h"
#include "lwip/nettool/misc.h"
#include "lwip/ip4_addr.h"
#include "lwip/netif.h"
#include "lwip/netifapi.h"
#include "lwip/sockets.h"
#include "wifi_connect.h"
 
int g_sock_fd;
struct sockaddr_in g_send_addr;
socklen_t g_addr_length = sizeof(g_send_addr);

#define CONFIG_WIFI_SSID            "zzuli-student"
#define CONFIG_WIFI_PWD             "lmh050901"
#define CONFIG_SERVER_IP            "192.168.76.181"
#define CONFIG_SERVER_PORT          11111 

/* 通知回调 - 处理ADC数据和串口数据 */
void sle_uart_notification_cb(uint8_t client_id, uint16_t conn_id, ssapc_handle_value_t *data,
    errcode_t status)
{
    unused(client_id);
    unused(conn_id);
    unused(status);
    
    if (data->data_len > 0) {
        osal_printk("\n sle uart received data : %s\r\n", data->data);
        uapi_uart_write(CONFIG_SLE_GATEWAY_BUS, (uint8_t *)(data->data), data->data_len, 0);
        sendto(g_sock_fd, (uint8_t *)(data->data), data->data_len, 0, (struct sockaddr *)&g_send_addr, g_addr_length);
    }
}
 
void sle_uart_indication_cb(uint8_t client_id, uint16_t conn_id, ssapc_handle_value_t *data,
    errcode_t status)
{
    unused(client_id);
    unused(conn_id);
    unused(status);
    osal_printk("\n sle uart received data : %s\r\n", data->data);
    uapi_uart_write(CONFIG_SLE_GATEWAY_BUS, (uint8_t *)(data->data), data->data_len, 0);
}
 
static void sle_uart_client_read_int_handler(const void *buffer, uint16_t length, bool error)
{
    unused(error);
    ssapc_write_param_t *sle_uart_send_param = get_g_sle_uart_send_param();
    uint16_t g_sle_uart_conn_id = get_g_sle_uart_conn_id();
    sle_uart_send_param->data_len = length;
    sle_uart_send_param->data = (uint8_t *)buffer;
    ssapc_write_req(0, g_sle_uart_conn_id, sle_uart_send_param);
}
 
static void *sle_uart_client_task(const char *arg)
{
    unused(arg);
    char recvBuf[512];
    uart_init_config();
 
    wifi_connect(CONFIG_WIFI_SSID, CONFIG_WIFI_PWD);
 
    printf("create socket start!\r\n");
    if ((g_sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        printf("create socket failed!\r\n");
        return 0;
    }
    g_send_addr.sin_family  = AF_INET;
    g_send_addr.sin_port  = htons(CONFIG_SERVER_PORT);
    g_send_addr.sin_addr.s_addr  = inet_addr(CONFIG_SERVER_IP);
    g_addr_length = sizeof(g_send_addr);
    printf("create socket end!\r\n");
 
    uapi_uart_unregister_rx_callback(CONFIG_SLE_GATEWAY_BUS);
    errcode_t ret = uapi_uart_register_rx_callback(CONFIG_SLE_GATEWAY_BUS,
                                                   UART_RX_CONDITION_FULL_OR_SUFFICIENT_DATA_OR_IDLE,
                                                   1, sle_uart_client_read_int_handler);
    sle_uart_client_init(sle_uart_notification_cb, sle_uart_indication_cb);
    
    if (ret != ERRCODE_SUCC) {
        osal_printk("Register uart callback fail.");
        return NULL;
    }
    while (1) {
        bzero(recvBuf, sizeof(recvBuf));
        recvfrom(g_sock_fd, recvBuf, sizeof(recvBuf), 0, (struct sockaddr *)&g_send_addr, &g_addr_length);
        ssapc_write_param_t *sle_uart_send_param = get_g_sle_uart_send_param();
        uint16_t g_sle_uart_conn_id = get_g_sle_uart_conn_id();
        sle_uart_send_param->data_len = strlen(recvBuf);
        sle_uart_send_param->data = (uint8_t *)recvBuf;
        ssapc_write_req(0, g_sle_uart_conn_id, sle_uart_send_param);
    }
    return NULL;
}

/* --------------------- 主入口函数 --------------------- */
#endif  /* CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_CLIENT */
 
static void sle_uart_entry(void)
{
    osal_task *task_handle = NULL;
    osal_kthread_lock();
    
#if defined(CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_SERVER) && (!defined(CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_CLIENT) || CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_CLIENT == 0)
    task_handle = osal_kthread_create((osal_kthread_handler)sle_uart_server_task, 
                                    0, "SLEUartServerTask", SLE_GATEWAY_TASK_STACK_SIZE);
#elif defined(CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_CLIENT) && CONFIG_SAMPLE_SUPPORT_SLE_GATEWAY_CLIENT == 1
    task_handle = osal_kthread_create((osal_kthread_handler)sle_uart_client_task, 
                                    0, "SLEUartClientTask", SLE_GATEWAY_TASK_STACK_SIZE);
#endif
    
    if (task_handle != NULL) {
        osal_kthread_set_priority(task_handle, SLE_GATEWAY_TASK_PRIO);
    }
    
    osal_kthread_unlock();
}
 
/* Run the sle_uart_entry. */
app_run(sle_uart_entry);

